//
//  File.swift
//  Remote_swift
//
//  Created by bbj on 2020/8/11.
//  Copyright © 2020 shian. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON


enum API {
    //个人中心模块

    case login(parameters:[String: Any])
    case loginBycode([String:Any])
    case messageCode([String:Any])
    case home //首页
    
    //机票模块
    case airIndex
    case getCity  //获取城市
    case getCityCodeByName([String:Any])
    case getHotcity
    case searchTicket(parameters:[String: Any])
    case searchPrice(parameters:[String: Any])
    case searchBK([String:Any])
    case airTicketOrder([String:Any])
    
    case getPassager(parameters:[String: Any])
    case addPassager([String:Any])
    case editPassager([String:Any])
    case getBaoxian([String:Any])
    case notice
    case searchPriceByday([String:Any])
    case baoxian
    case orderNotice
    case wxPay([String:Any])
    case uploadAvatarImgae(parametersDict:[String : Any],imageData : Array<Data>)//头像上传
    case upload_identityimg(parametersDict:[String : Any],imageData : Array<Data>)
    case uploadfile(fileURL:URL)
}

extension API:TargetType{
    
    var baseURL: URL {
        return URL(string: "http://swoole.whichzhen.com")!
    }
    
    //具体请求路径
    var path: String {
        switch self {
      
    
        case .login:
            return "/api/user/login"
        case .messageCode:
            return "/api/sms/send"
        case .loginBycode:
            return  "/api/user/mobilelogin"
        case .home:
            return "/api/flight/index"
        case .searchTicket:
            return "/api/flight/searchFlight"
      
        case .getCity:
            return "/api/flight/getCityCode"
        case .getCityCodeByName:
            return "/api/flight/getCityCodeByName"
        case .getHotcity:
            return "/api/flight/getHotCity"
        case .searchPrice:
            return "/api/flight/searchPrice"
        case  .searchBK:
            return "/api/flight/searchBK"
        case .airTicketOrder:
            return "/api/flight/ticketOrder"
        case .orderNotice:
            return "/api/flight/notice?type=2"
        case .airIndex:
            return "/api/flight/index"
        case .getPassager:
            return "/api/user/gitIdCardList"
        case .addPassager:
            return "/api/user/addUserIdCard"
        case .editPassager:
            return "/api/user/updateUserIdCard"
        case .getBaoxian:
            return "/api/travelData/getInsuranceProduct"
        case .notice:
            return "/api/flight/notice"
        case .searchPriceByday:
            return "/api/flight/searchPriceCalendar"
        case .baoxian:
            return "/api/flight/insurance"
        case .wxPay:
            return "/api/flight/orderPay"
            
        case .uploadAvatarImgae:
            return ""
        case .upload_identityimg:
            return "/api/user/identityimg"
            
        case .uploadfile:
            return ""
        }
     
    }
    
    var getPartmeters: [String: Any]?{
        
        switch self {
  
        case let .login(dic):
            return dic
        case let .messageCode(dic):
            return dic
        case let .loginBycode(dic):
            return dic
        case .home:
            return nil
        case .airIndex:
            return nil
        
        case  .getCity:
            return nil
        case let .getCityCodeByName(dic):
            return dic
        case .getHotcity:
            return nil
        case let .searchTicket(dic):
            return dic
        case let .searchPrice(parameters: dic):
            return dic
        case let .searchBK(dic):
            return dic
        case let .airTicketOrder(dic):
            return dic
            
        case let .getPassager(dic):
            return dic
        case let .addPassager(dic):
            return dic
        case let .editPassager(dic):
            return dic
        case let .getBaoxian(dic):
            return dic
        case .notice:
            return nil
        case .orderNotice:
            return nil
        case let .searchPriceByday(dic):
            return dic
        case .baoxian:
            return nil
        case let .wxPay(dic):
            return dic
            
        case .upload_identityimg:
            return nil
      
        case .uploadAvatarImgae:
            return nil
       
        case  .uploadfile(fileURL: _):
             return nil
       
        
        }
    }
    
   
  
    //请求方式
    var method: Moya.Method {
        switch self{
       
        default:
            return .post
        }
       
    }
    //请求任务
    var task: Task {
            
        switch self {
        case .upload_identityimg(let parameters, let imageData):
            var imageArray:Array<MultipartFormData> = []
            for data in imageData {
                let formData = MultipartFormData(provider: .data(data), name: "file",
                fileName: "post.png", mimeType: "image/png")
                imageArray.append(formData)
            }
            
            return .uploadCompositeMultipart(imageArray, urlParameters: parameters)

        case .uploadAvatarImgae( let parameters, let imageData):
            var imageArray:Array<MultipartFormData> = []
            for data in imageData {
                let formData = MultipartFormData(provider: .data(data), name: "file",
                fileName: "post.png", mimeType: "image/png")
                imageArray.append(formData)
            }
            
            return .uploadCompositeMultipart(imageArray, urlParameters: parameters)
            
        case  .uploadfile(let fileURL):
            var fileArr:Array<MultipartFormData>=[]
            let formData = MultipartFormData(provider: .file(fileURL), name: "file",fileName: "h.wav", mimeType: "mp3/wav")
            fileArr.append(formData)
            
           return .uploadMultipart(fileArr)
            
        
        default:
            print(getPartmeters,"参数")
            //return .requestParameters(parameters: getPartmeters ?? [:] , encoding: ParameterEncoding.self as! ParameterEncoding)
            return .requestParameters(parameters: getPartmeters ?? [:], encoding: URLEncoding.httpBody)
            
        }
     
            
  
      }
    
    var sampleData: Data {
        return Data()
    }
    
    var headers: [String : String]? {
        let token=UserDefaults.standard.value(forKey: "token") as? String ?? ""
       // let Btoken="Bearer " + token
      //  return ["Content-Type":"application/x-www-form-urlencoded","token":token]
        return["token":token]
    }
    
}






/// 超时时长
private var requestTimeOut:Double = 30

///endpointClosure
private let myEndpointClosure = { (target: API) -> Endpoint in
    ///主要是为了解决URL带有？无法请求正确的链接地址的bug
    let url:String!
    if target.path.contains("http://") || target.path.contains("https://") {
        url=target.path
    }else{
        url = target.baseURL.absoluteString + target.path
    }
    
    var endpoint = Endpoint(
        url: url,
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        task: target.task,
        httpHeaderFields: target.headers
    )
    print(url,"请求地址")
    switch target {
//    case .login:
//        requestTimeOut = 10//按照项目需求针对单个API设置不同的超时时长
//        return endpoint
    default:
        requestTimeOut = 60//设置默认的超时时长
        return endpoint
    }
}


struct Network {
    static let provider = MoyaProvider<API>(endpointClosure: myEndpointClosure)
    
    static func request(_ target: API, successCallback: @escaping (JSON) -> Void,
                        failure failureCallback: @escaping (String) -> Void){
        
//        YProgressHUD.show()
        
        provider.request(target) { (result) in
            
            switch result{
            case let .success(response):
                print(response,"-------")
                guard let json=try? JSON(data: response.data) else {
                    print("服务器连接成功,数据获取失败")
                    YProgressHUD.dismiss()
                    return
                }
                let code = json["code"].int
                    if(code==200 || code == 1){
                        YProgressHUD.dismiss()
                        successCallback(json)
                        
                        }
                    else if(code == 400){
                        YProgressHUD.showToast(json["msg"].string)
                       // successCallback(json)
                        
                    }
                    else if(code == 0){
                        YProgressHUD.showToast(json["msg"].string)
                        successCallback(json)
                        
                    }

                    else if (code == 401) {
                        let vc=Login_PWD_VC.init()
                        getCurrentVc().navigationController?.pushViewController(vc, animated: true)

                        }
                    else{
                        YProgressHUD.showToast(json["msg"].string)
                        
                    }
                
            case let .failure(error):
                failureCallback(error.errorDescription!)
        
                YProgressHUD.showToast("请检查网络连接")

            }
        }
    }
    // MARK: - 取消所有网络请求
//    static func cancelAllRequest(){
//        provider.session.getAllTasks { (tasks) in
//            tasks.forEach{
//                print("取消网络请求一次")
//                $0.cancel()
//            }
//        }
//    }
    
    
    
}


